<?php
//增加支付单
function pay_add($user, $order) {
	global $db;
	$cache_payment = cache::get('payment');
	$sql_set['pay_id'] = $pay_id = pe_guid('pay|pay_id', 'pay');
	$sql_set['pay_type'] = $order['pay_type'];
	$sql_set['order_id'] = is_array($order['order_id']) ? implode(',', $order['order_id']) : $order['order_id'];
	$sql_set['order_name'] = $order['order_name'];
	$sql_set['order_money'] = $order['order_money'];
	$order['order_data'] && $sql_set['order_data'] = json_encode($order['order_data']);
	$sql_set['order_atime'] = time();
	$sql_set['order_payment'] = $order['order_payment'];
	$sql_set['order_payment_name'] = $cache_payment[$order['order_payment']]['payment_name'];
	$sql_set['user_id'] = $user['user_id'];
	$sql_set['user_name'] = $user['user_name'];
	if ($db->pe_insert('pay', pe_dbhold($sql_set, array('order_data')))) {
		return $pay_id;
	}
	else {
		return false; 
	}
}

//支付成功操作
function pay_success($pay, $order_payment = '', $order_outid = '') {
	global $db;
	$cache_payment = cache::get('payment');
	$info = is_array($pay) ? $pay : $db->pe_select('pay', array('pay_id'=>pe_dbhold($pay)));
	if (!$info['pay_id']) return false;
	if ($info['order_state'] != 'wpay') return false;
	if (!$order_payment) $order_payment = $info['order_payment'];
	if ($order_payment == 'balance') {
		add_moneylog($info['user_id'], 'order_pay', $info['order_money'], "支付订单扣除，交易编号【{$info['pay_id']}】");
	}
	if ($order_outid) $sql_set['order_outid'] = $order_outid;
	$sql_set['order_state'] = 'success';
	$sql_set['order_payment'] = $info['order_payment'] = $order_payment;
	$sql_set['order_payment_name'] = $info['order_payment_name'] = $cache_payment[$order_payment]['payment_name'];
	$sql_set['order_ptime'] = $info['order_ptime'] = time();
	$sql_set['order_pstate'] = $info['order_pstate'] = 1;
	if ($db->pe_update('pay', array('pay_id'=>$info['pay_id']), pe_dbhold($sql_set))) {
		$order_data = $info['order_data'] ? json_decode($info['order_data'], true) : array();
		switch ($info['pay_type']) {
			case 'recharge':
				add_moneylog($info['user_id'], 'recharge', $info['order_money'], "会员钱包充值{$info['order_money']}元 - {$info['order_payment_name']}");
			break;	
			default:
				order_pay_callback($info['order_id'], $info);
			break;
		}
		return true;
	}
	return false;
}

//订单支付后跳转
function pay_jump($pay_id) {
	global $db, $pe;
	$info = $db->pe_select('pay', array('pay_id'=>$pay_id));
	$order_data = $info['order_data'] ? json_decode($info['order_data'], true) : array();
	if ($info['pay_type'] == 'recharge') {
		if (pe_mobile()) {
 			$url = "/page/user/moneylog_list";	
		}
		else {
			$url = "{$pe['host']}user.php?mod=moneylog";		
		}
	}
	else {
		if (pe_mobile()) {
            $url = "/page/user/order_list";
        }
        else {
            $url = "{$pe['host']}user.php?mod=order";
        }
	}
	return $url;
}
?>